from django.views import View
from django.http import JsonResponse
from public import lib_compress, decompress
import json, uuid
from json.decoder import JSONDecodeError
from system.models import NovelModel, ChapterModel

version = '0.1'


class IssueBook(View):  # 发布书
    def post(self, request):
        request_data = request.body
        try:
            request_dict = json.loads(request_data.decode('utf-8'))
        except JSONDecodeError as e:
            return JsonResponse({'code': 4, 'msg': f'请求数据为空,解析失败[info:{str(e)}]'})
        novel_name = request_dict.get('novel_name', '').replace(' ', '').lower()
        n = NovelModel.objects.filter(novel_name=novel_name, is_delete=False)
        if n.count(): return JsonResponse({'code': 1, 'msg': '发布书本已存在！', 'version': version, 'uid': n.first().uuid})
        request_dict.update({'uuid': uuid.uuid4(), 'novel_name': novel_name})
        result = NovelModel.objects.create(**request_dict)  # 创建数据
        return JsonResponse({'code': 0, 'msg': 'success', 'version': version, 'uid': result.uuid})


class IssueChapter(View):  # 发布章节
    def post(self, request):
        request_data = request.body
        try:
            request_dict = json.loads(request_data.decode('utf-8'))
        except JSONDecodeError as e:
            return JsonResponse({'code': 4, 'msg': '请求数据为空,解析失败'})
        c = ChapterModel.objects.filter(title=request_dict['title'], novel=request_dict['novel_id'], is_delete=False)
        if c.count(): return JsonResponse({'code': 1, 'msg': '发布书本已存在！', 'version': version, 'uid': c.first().content_id})
        content = request_dict['content']
        content_id, content_path = lib_compress(content)
        data = {'uuid': uuid.uuid4(), 'title': request_dict['title'], 'novel_id': request_dict['novel_id'], 'is_pay': request_dict.get('is_pay', False), 'content_id': content_id,
                'content_path': content_path}
        result = ChapterModel.objects.create(**data)  # decompress(result.content_path,result.content_id) # 解码
        return JsonResponse({'code': 0, 'msg': 'success', 'version': version, 'cid': result.uuid})
